package com.iakuil.mvp.mp.common.util;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/***
 * 数组集合切割工具类
 *
 * @author Kai
 */
public class Splitter {

    public static <T> List<T[]> split(T[] original, int groupSize) {
        List<T[]> result = new ArrayList<>();
        if (original == null) {
            return result;
        }

        int curPos = 0;
        while (curPos < original.length) {
            int remaining = original.length - curPos + 1;
            if (remaining <= groupSize) {
                result.add(Arrays.copyOfRange(original, curPos, original.length));
            } else {
                result.add(Arrays.copyOfRange(original, curPos, curPos + groupSize));
            }
            curPos += groupSize;
        }

        return result;
    }

    public static <T> List<List<T>> split(List<T> list, int groupSize) {
        int length = list.size();
        // 计算可以分成多少组
        int num = (length + groupSize - 1) / groupSize;
        List<List<T>> result = new ArrayList<>(num);
        for (int i = 0; i < num; i++) {
            // 开始位置
            int fromIndex = i * groupSize;
            // 结束位置
            int toIndex = Math.min((i + 1) * groupSize, length);
            result.add(list.subList(fromIndex, toIndex));
        }

        return result;
    }
}
